package cate.game.event.master;

import cate.game.event.GameEventListener;
import cate.game.role.Role;
import cate.game.util.api.StatApi;
import cate.game.util.api.WorldApi;
import cp.solution.util.time.TimeCostRecord;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RoleLoginListener implements GameEventListener<RoleLoginEvent> {
    @Override
    public void onEvent(RoleLoginEvent gameEvent) {
        Role role = gameEvent.role;
        role.entering = true;
        try {
            try {
                if(role.getBase().merge.happened) {
                    TimeCostRecord tcr = new TimeCostRecord();
                    role.onMergeSettle(role.getGame(), tcr);
                }
            } catch (Exception e) {
                log.error("", e);
            }

            //这里一定不能调用synchronized方法,否则可能死锁
            safe(() -> role.getStatus().active(), "getStatus().active()");
            safe(() -> role.getStatus().checkTimeSpans(), "getStatus().checkTimeSpans()");
            safe(() -> role.getStatus().onEnter(), "getStatus().onEnter()");
            if (!gameEvent.first) {
                safe(() -> role.getGame().rank.updateRole(role),"rank.updateRole(role)");
            }
            safe(() -> role.getTask().onEnter(), "getTask().onEnter");
            safe(() -> role.getFarm().onEnter(),"getFarm().onEnter");
            safe(() -> role.getActivity().onEnter(),"getActivity().onEnter");
            safe(() -> role.getShow().onEnter(),"getShow().onEnter");
            safe(() -> role.getPvp().onEnter(),"getPvp().onEnter");
            safe(() -> role.getMail().onEnter(),"getMail().onEnter");
            safe(() -> role.getRes().onEnter(),"getRes().onEnter");
            if (!gameEvent.first) {
                safe(() -> role.getFriend().onEnter(),"getFriend().onEnter");
            }
            safe(() -> role.getPay().onEnter(), "getPay().onEnter");
            safe(() -> role.getBag().onEnter(), "getBag().onEnter");
            safe(() -> role.getWorld().onEnter(), "getWorld().onEnter");
            safe(() -> role.getTrace().onEnter(), "getTrace().onEnter");
            // 最后做统计
            safe(() -> StatApi.updateRoleRecord(role), "StatApi.updateRoleRecord(role)");
            safe(() -> WorldApi.updateActiveRole(role.getGame(), role), "WorldApi.updateActiveRole(role)");
            safe(() -> role.getBase().onEnter(), "base.onEnter");
        } finally {
            role.entering = false;
            role.getBase().merge.happened = false;
        }
    }

    // 自己报自己的错，放过别人的代码吧
    private static void safe(Runnable runnable, String description) {
        try {
            runnable.run();
        } catch (Exception e) {
            log.error("{} 执行发生了错误", description);
            log.error("", e);
        }
    }
}
